package org.jeecg.modules.demo.hd.service.impl;

import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.demo.hd.entity.AppConfig;
import org.jeecg.modules.demo.hd.entity.AppMyProjectClickdetail;
import org.jeecg.modules.demo.hd.entity.AppUserGoldDetail;
import org.jeecg.modules.demo.hd.mapper.AppUserGoldDetailMapper;
import org.jeecg.modules.demo.hd.service.IAppConfigService;
import org.jeecg.modules.demo.hd.service.IAppUserGoldDetailService;
import org.jeecg.modules.demo.hd.service.IAppUserGoldMainService;
import org.jeecg.modules.demo.hd.vo.UserDayGoldTotalVo;
import org.jeecg.modules.demo.hd.vo.UserDayGoldTypeTotalVo;
import org.jeecg.modules.demo.hd.vo.total.ChildUserGoldInputVo;
import org.jeecg.modules.demo.hd.vo.total.ChildUserGoldViewVo;
import org.jeecg.modules.demo.hd.vo.total.UserGoldDetailViewVo;
import org.jeecg.modules.demo.hd.vo.userGoldDetailModelVo;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @Description: 用户金币明细操作
 * @Author: jeecg-boot
 * @Date: 2025-02-04
 * @Version: V1.0
 */
@Service
public class AppUserGoldDetailServiceImpl extends ServiceImpl<AppUserGoldDetailMapper, AppUserGoldDetail> implements IAppUserGoldDetailService {

    @Resource
    private IAppUserGoldMainService appUserGoldMainService;

    @Resource
    private ISysUserService userService;

    @Resource
    private IAppConfigService appConfigService;

    @Override
    @Transactional
    public String addDetail(userGoldDetailModelVo vo) {
        LoginUser currentUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String userId = currentUser.getId();
        AppUserGoldDetail model = new AppUserGoldDetail();
        BeanUtils.copyProperties(vo, model);
        model.setUserId(userId);
        model.setGoldStatus("1");
        this.baseMapper.insert(model);
        //查询该用户下状态为1的所有记录
        QueryWrapper<AppUserGoldDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("gold_status", "1");
        List<AppUserGoldDetail> appUserGoldDetail2s = this.baseMapper.selectList(queryWrapper);
        float n = 0;
        for (AppUserGoldDetail num : appUserGoldDetail2s) {
            n += num.getGoldNum();
        }
        //更新总金币数量
        appUserGoldMainService.updateCurrentGold(n);
        return null;
    }

    @Override
    @Transactional
    public String addNewDetail() {
        LoginUser currentUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String userId = currentUser.getId();
        SysUser userInfo = userService.getById(userId);
        // 默认金币5000，补贴金币5000
        AppUserGoldDetail goldDetailModel = new AppUserGoldDetail();
        goldDetailModel.setEcpm(0);
        goldDetailModel.setGoldNum(5000);
        goldDetailModel.setSubsidyNum(5000);            // 2025年5月5日后，无补助金币
        goldDetailModel.setGoldStatus("1");
        goldDetailModel.setBonusTime(DateUtils.getDate());
        goldDetailModel.setUserId(userId);
        goldDetailModel.setName("激励广告获得金币");
        goldDetailModel.setProjectId("");
        goldDetailModel.setRequestId("");
        goldDetailModel.setGoldType("0");
        goldDetailModel.setDepId(userInfo.getOrgCode());    // 奖励添加到团队
        goldDetailModel.setCode(UUID.randomUUID().toString(true));
        this.baseMapper.insert(goldDetailModel);
        appUserGoldMainService.updateGoldMain(userId, 5000);
        return goldDetailModel.getCode();
    }

    /**
     * 点击广告完成后，向用户发放金币
     * 用户每天点击广告额外送10次金币，金币可兑换工币。每次额外送1万金币。
     * 先根据code  查询原始记录，
     *
     * @param model
     * @return
     */
    @Override
    @Transactional
    public Integer addGoldDetail(AppMyProjectClickdetail model) {
        // 获取当前用户，根据当前广告收益，按照规则是否补贴金币
        SysUser userInfo = userService.getById(model.getUserId());
        // 获取用户抽佣比例
        double commissionRate = userInfo.getCommissionRate();
        if (commissionRate <= 0.3)
            commissionRate = 0.5;
        if (commissionRate >= 0.5)
            commissionRate = 0.5;
        AppConfig config = appConfigService.getConfig();
        // 计算比例，算出金币数量
        double doubleEcpm = Double.parseDouble(model.getEcpm());
        int _ecpm = (int) Math.round(doubleEcpm);
        int goldNum = (int) (_ecpm * commissionRate * config.getRate());   //后台配置系数
        // TODO 是否开启红包雨，每条广告保底5000；  折后高于15000的 减5000（8点 10点 12点 14点 16点 18点 20点 22点） 0到30分
        if (config.getBlBd().equals(0)) {
            if (goldNum < 5000) {
                // 获取用户当天 当前设备ecpm低于5000 的条数。
                goldNum = 5000;
            } else if (goldNum >= 6000 && goldNum < 10000) {
                goldNum *= 0.9;
            } else if (goldNum >= 10000 && goldNum < 20000) {
                goldNum *= 0.8;
            } else if (goldNum >= 20000 && goldNum < 30000) {
                goldNum *= 0.7;
            }
        }
        // 开启上限控制
        if (config.getBlXg().equals(0)) {
            if (goldNum > 400000) {
                goldNum -= 12000;
            } else if (goldNum > 200000 && goldNum <= 400000) {
                goldNum -= 10000;
            } else if (goldNum > 100000 && goldNum <= 200000) {
                goldNum -= 8000;
            } else if (goldNum > 30000 && goldNum <= 100000) {
                goldNum -= 5000;
            } else if (goldNum > 10000 && goldNum <= 30000) {
                goldNum -= 1000;
            } else if (goldNum > 8000 && goldNum <= 10000) {
                goldNum -= 200;
            }
        }
        // TODO 用户单台设备 保底5000金币 40条；设置开启时间和关闭，保底金额和次数在配置文件中配置
        if (config.getBlDayBt().equals(0)) {
            if (goldNum <= config.getBtGold() && goldNum>1000) {
                // 获取用户ID 和 设备ID 补偿条数
                Integer count = this.quereUserGoldSubsidiesCount(model.getUserId(), model.getDeviceId(), DateUtils.getDate("yyyy-MM-dd"));
                if (count < config.getBtNum()) {
                    goldNum = config.getBtGold();
                }
            }
        }

        // 系统在2025-6-15日前每日向用户发放10次补贴金币，每次补贴1万
        AppUserGoldDetail goldDetailModel = new AppUserGoldDetail();
        goldDetailModel.setEcpm(_ecpm);
        goldDetailModel.setGoldNum(goldNum);
        goldDetailModel.setSubsidyNum(0);            // 2025年5月5日后，无补助金币
        goldDetailModel.setGoldStatus("1");
        goldDetailModel.setBonusTime(DateUtils.getDate());
        goldDetailModel.setUserId(model.getUserId());
        goldDetailModel.setName("激励广告获得金币");
        goldDetailModel.setProjectId(model.getProjectId());
        goldDetailModel.setRequestId(model.getRequestId());
        goldDetailModel.setGoldType("0");
        goldDetailModel.setDepId(userInfo.getOrgCode());    // 奖励添加到团队
        goldDetailModel.setDeviceId(model.getDeviceId());
        this.baseMapper.insert(goldDetailModel);
        // 判断日期是否在活动期内
        LocalDate currentDate = DateUtils.getLocalDate();
        LocalDate targetDate = LocalDate.of(2025, 6, 30);
        if (currentDate.isBefore(targetDate)) {
            if (userInfo.getOrgCode().equals("A03") || !userInfo.getOrgCode().equals("1919332301380452353")) {

            } else {
//                int subsidyCount = subsidyCount(model.getUserId());
//                if (subsidyCount < 10) {
//                    AppUserGoldDetail goldDetailModel2 = new AppUserGoldDetail();
//                    goldDetailModel2.setEcpm(0);
//                    goldDetailModel2.setGoldNum(10000);           //平台奖励金币，每次10000，每日奖励10次
//                    goldDetailModel2.setSubsidyNum(0);            // 2025年5月5日后，无补助金币
//                    goldDetailModel2.setGoldStatus("1");
//                    goldDetailModel2.setBonusTime(DateUtils.getDate());
//                    goldDetailModel2.setUserId(model.getUserId());
//                    goldDetailModel2.setName("平台奖励金币，仅限兑换工币用");
//                    goldDetailModel2.setProjectId(model.getProjectId());
//                    goldDetailModel2.setRequestId(model.getRequestId());
//                    goldDetailModel2.setGoldType("2");      //平台奖励金币，仅限兑换工币用
//                    this.baseMapper.insert(goldDetailModel2);
//                    goldNum += 10000;
//                }
            }
        }
        // 更新用户金币总额
        appUserGoldMainService.updateGoldMain(model, goldNum);
        return goldNum;
    }

    @Override
    public Integer addGoldDetail(AppMyProjectClickdetail model, String code) {
        // 获取当前用户，根据当前广告收益，按照规则是否补贴金币
        SysUser userInfo = userService.getById(model.getUserId());
        // 获取用户抽佣比例
        double commissionRate = userInfo.getCommissionRate();
        if (commissionRate <= 0.3)
            commissionRate = 0.5;
        // 计算比例，算出金币数量
        double doubleEcpm = Double.parseDouble(model.getEcpm());
        int _ecpm = (int) Math.round(doubleEcpm);
        int goldNum = (int) (_ecpm * commissionRate);
        // 系统在2025-6-15日前每日向用户发放10次补贴金币，每次补贴1万
        // 根据code 查询 golddetail
        AppUserGoldDetail goldDetailModel = getGoldDetailByCode(code);
        goldDetailModel.setEcpm(_ecpm);
        goldDetailModel.setGoldNum(goldNum);
        goldDetailModel.setSubsidyNum(0);            // 2025年5月5日后，无补助金币
        goldDetailModel.setGoldStatus("1");
        goldDetailModel.setBonusTime(DateUtils.getDate());
        goldDetailModel.setUserId(model.getUserId());
        goldDetailModel.setName("激励广告获得金币");
        goldDetailModel.setProjectId(model.getProjectId());
        goldDetailModel.setRequestId(model.getRequestId());
        goldDetailModel.setGoldType("0");
        goldDetailModel.setDepId(userInfo.getDepartIds());    // 奖励添加到团队
        this.baseMapper.insert(goldDetailModel);
        // 判断日期是否在活动期内
        LocalDate currentDate = DateUtils.getLocalDate();
        LocalDate targetDate = LocalDate.of(2025, 6, 30);
//        if (currentDate.isBefore(targetDate)) {
//            int subsidyCount = subsidyCount(model.getUserId());
//            if (subsidyCount < 10) {
//                AppUserGoldDetail goldDetailModel2 = new AppUserGoldDetail();
//                goldDetailModel2.setEcpm(0);
//                goldDetailModel2.setGoldNum(10000);           //平台奖励金币，每次10000，每日奖励10次
//                goldDetailModel2.setSubsidyNum(0);            // 2025年5月5日后，无补助金币
//                goldDetailModel2.setGoldStatus("1");
//                goldDetailModel2.setBonusTime(DateUtils.getDate());
//                goldDetailModel2.setUserId(model.getUserId());
//                goldDetailModel2.setName("平台奖励金币，仅限兑换工币用");
//                goldDetailModel2.setProjectId(model.getProjectId());
//                goldDetailModel2.setRequestId(model.getRequestId());
//                goldDetailModel2.setGoldType("2");      //平台奖励金币，仅限兑换工币用
//                this.baseMapper.insert(goldDetailModel2);
//                goldNum += 10000;
//            }
//        }
        // 更新用户金币总额
        appUserGoldMainService.updateGoldMain(model, goldNum);
        return goldNum;
    }

    @Override
    @Transactional
    public String exchangeCash(String userId, double goldNum) {
        AppUserGoldDetail goldDetailModel = new AppUserGoldDetail();
        goldDetailModel.setEcpm(0);
        goldDetailModel.setGoldNum((int) goldNum);
        goldDetailModel.setGoldStatus("1");
        goldDetailModel.setBonusTime(DateUtils.getDate());
        goldDetailModel.setUserId(userId);
        goldDetailModel.setName("兑换现金");
        goldDetailModel.setProjectId("");
        goldDetailModel.setRequestId("");
        goldDetailModel.setGoldType("1");      //1 兑换现金扣除金币
        this.baseMapper.insert(goldDetailModel);
        // 更新用户金币总额
        appUserGoldMainService.updateGoldMain(userId, (int) goldNum);
        return null;
    }

    @Override
    public AppMyProjectClickdetail getLastDetail(String userId) {
        LambdaQueryWrapper<AppUserGoldDetail> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(AppUserGoldDetail::getUserId, userId);
        queryWrapper.eq(AppUserGoldDetail::getGoldType, "0");       // 用户点击广告获得奖励
        List<AppUserGoldDetail> goldDetails = this.baseMapper.selectList(queryWrapper);


        return null;
    }

    @Override
    @Transactional
    public String commissionGold(String userId, double goldNum, String goldType) {
        AppUserGoldDetail goldDetailModel = new AppUserGoldDetail();
        goldDetailModel.setEcpm(0);
        goldDetailModel.setGoldNum((int) goldNum);
        goldDetailModel.setGoldStatus("1");
        goldDetailModel.setBonusTime(DateUtils.getDate());
        goldDetailModel.setUserId(userId);
        goldDetailModel.setName("团队提成奖励");
        goldDetailModel.setProjectId("");
        goldDetailModel.setRequestId("");
        goldDetailModel.setGoldType(goldType);
        this.baseMapper.insert(goldDetailModel);
        // 更新用户金币总额
        appUserGoldMainService.updateGoldMain(userId, (int) goldNum);
        return null;
    }

    @Override
    @Transactional
    public String exchangeShare(String userId, double goldNum) {
        AppUserGoldDetail goldDetailModel = new AppUserGoldDetail();
        goldDetailModel.setEcpm(0);
        goldDetailModel.setGoldNum((int) goldNum);
        goldDetailModel.setGoldStatus("1");
        goldDetailModel.setBonusTime(DateUtils.getDate());
        goldDetailModel.setUserId(userId);
        goldDetailModel.setName("兑换工币");
        goldDetailModel.setProjectId("");
        goldDetailModel.setRequestId("");
        goldDetailModel.setGoldType("3");      //3 兑换工币扣除金币
        this.baseMapper.insert(goldDetailModel);
        // 更新用户金币总额
        appUserGoldMainService.updateGoldMain(userId, (int) goldNum);
        return null;
    }

    @Override
    public void clean() {
        this.baseMapper.delete(null);
    }

    @Override
    public List<UserDayGoldTotalVo> getUserDayGoldTotalList(String day) {
        List<UserDayGoldTotalVo> list = this.baseMapper.getUserDayGoldTotalList(day);
        return list;
    }

    @Override
    public Double getCurrentUserDayGold() {
        LoginUser currentUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String userId = currentUser.getId();
        LocalDateTime startOfDay = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0).withNano(0);
        LocalDateTime endOfDay = LocalDateTime.now().withHour(23).withMinute(59).withSecond(59).withNano(999999999);
        LambdaQueryWrapper<AppUserGoldDetail> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.between(AppUserGoldDetail::getCreateTime, startOfDay, endOfDay);
        queryWrapper.eq(AppUserGoldDetail::getUserId, userId);
        queryWrapper.eq(AppUserGoldDetail::getGoldType, "0");       // 用户点击广告获得奖励
        List<AppUserGoldDetail> goldDetails = this.baseMapper.selectList(queryWrapper);
        Double sum = goldDetails.stream().mapToDouble(AppUserGoldDetail::getGoldNum).sum();
        return sum;
    }

    @Override
    public Double quereUserGoldTotalByDay(String day, String userId) {
        return this.baseMapper.quereUserGoldTotalByDay(day, userId);
    }

    @Override
    public Double quereUserGoldTotalByDayForSettlement(String day, String userId) {
        return this.baseMapper.quereUserGoldTotalByDayForSettlement(day, userId);
    }

    @Override
    public List<UserDayGoldTypeTotalVo> getUserDayGoldTypeTotalList() {
        String date = DateUtils.getDate("yyyy-MM-dd");
        List<UserDayGoldTypeTotalVo> userDayGoldTypeTotalList = this.baseMapper.getUserDayGoldTypeTotalList(date);
        return userDayGoldTypeTotalList;
    }

    @Override
    public IPage<ChildUserGoldViewVo> getChildUserGoldNumTotalList(String genCode, String day, IPage page) {
        List<ChildUserGoldViewVo> list = baseMapper.getChildUserGoldNumTotalList(page, genCode, day);
        Integer total = baseMapper.getChildUserGoldNumTotal(genCode, day);
        IPage<ChildUserGoldViewVo> result = new Page<>(page.getCurrent(), page.getSize(), total);
        result.setRecords(list);
        return result;

    }

    @Override
    public ChildUserGoldViewVo getChildUserGoldNumTotal(String genCode, String day) {
        ChildUserGoldViewVo childUserGoldViewVo = baseMapper.queryChildUserGoldTotalModel(genCode, day);
        return childUserGoldViewVo;
    }

    @Override
    public IPage<UserGoldDetailViewVo> getUserGoldDetailList(ChildUserGoldInputVo vo, IPage page) {
        List<UserGoldDetailViewVo> list = baseMapper.getUserGoldDetailList(page, vo);
        Integer total = baseMapper.getUserGoldDetailTotal(vo);
        IPage<UserGoldDetailViewVo> result = new Page<>(page.getCurrent(), page.getSize(), total);
        result.setRecords(list);
        return result;
    }

    @Override
    public List<UserGoldDetailViewVo> getAllUserGoldDetailList(ChildUserGoldInputVo vo) {
        List<UserGoldDetailViewVo> userGoldDetailList = baseMapper.queryUserGoldTotalList2(vo);
        return userGoldDetailList;
    }

    @Override
    public IPage<ChildUserGoldViewVo> getUserGoldTotalList(ChildUserGoldInputVo vo, IPage page) {
        List<ChildUserGoldViewVo> list = baseMapper.queryUserGoldTotalList(page, vo);
        Integer total = baseMapper.queryUserGoldTotal(vo);
        IPage<ChildUserGoldViewVo> result = new Page<>(page.getCurrent(), page.getSize(), total);
        result.setRecords(list);
        return result;
    }

    @Override
    @Transactional
    public Boolean updateGoldState(String userId, String day) {
        baseMapper.updateGoldState(day, userId);
        return true;
    }

    /**
     * 查询 近7天的 金币获取记录
     *
     * @param deviceId
     * @param page
     * @return
     */
    @Override
    public IPage<UserGoldDetailViewVo> getUserGoldList(String deviceId, String userId, String day, IPage page) {
        List<UserGoldDetailViewVo> list = baseMapper.getUserGoldList(deviceId, userId, day, page);
        Integer total = baseMapper.getUserGoldListTotal(deviceId, userId, day);
        IPage<UserGoldDetailViewVo> result = new Page<>(page.getCurrent(), page.getSize(), total);
        result.setRecords(list);
        return result;
    }

    @Override
    public Integer quereUserGoldSubsidiesCount(String userId, String deviceId, String day) {
        return this.baseMapper.quereUserGoldSubsidiesCount(userId, deviceId, day);
    }


    /**
     * 获取用户当天获得金币奖励次数
     * 用户活动期间每天可获得10次平台奖励
     *
     * @param userId
     * @return
     */
    private int subsidyCount(String userId) {
        // 设置查询当天的数据范围
        LocalDateTime startOfDay = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0).withNano(0);
        LocalDateTime endOfDay = LocalDateTime.now().withHour(23).withMinute(59).withSecond(59).withNano(999999999);
        LambdaQueryWrapper<AppUserGoldDetail> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.between(AppUserGoldDetail::getCreateTime, startOfDay, endOfDay);
        queryWrapper.eq(AppUserGoldDetail::getUserId, userId);
        queryWrapper.eq(AppUserGoldDetail::getGoldType, "2");       //平台奖励金币，仅限兑换工币用
        List<AppUserGoldDetail> goldDetails = this.baseMapper.selectList(queryWrapper);
        return goldDetails.size();
    }


    private AppUserGoldDetail getGoldDetailByCode(String code) {
        LambdaQueryWrapper<AppUserGoldDetail> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(AppUserGoldDetail::getCode, code);
        List<AppUserGoldDetail> goldDetails = this.baseMapper.selectList(queryWrapper);
        if (goldDetails.size() > 0) {
            return goldDetails.get(0);
        }
        return new AppUserGoldDetail();
    }


}
